#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python常用模块库 
@File ：udp_protocol.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/20 上午12:16 
"""

import logging
import socket
from typing import Callable, Any


class UDPProtocol:
	def __init__(self, host: str, port: int, callback: Callable[[bytes], Any] = None):
		self.host = host
		self.port = port
		self.callback = callback
		self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.running = False

	def start(self):
		"""启动UDP服务器"""
		self.socket.bind((self.host, self.port))
		self.running = True
		logging.info(f"UDP server started on {self.host}:{self.port}")
		while self.running:
			data, addr = self.socket.recvfrom(1024)
			if self.callback:
				self.callback(data)

	def stop(self):
		"""停止UDP服务器"""
		self.running = False
		self.socket.close()
		logging.info("UDP server stopped.")

	def send(self, data: bytes) -> Any:
		"""发送UDP数据"""
		with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
			sock.sendto(data, (self.host, self.port))
			return sock.recvfrom(1024)
